package com.example.shuqishixi;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

@WebServlet(name = "updateUserServlet", value = "/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String currentUsername = (String) request.getSession().getAttribute("username");
        String role = (String) request.getSession().getAttribute("user_role");
        System.out.println("当前登录用户: " + currentUsername);
        System.out.println("用户角色: " + role);
        System.out.println("要修改的用户: " + username);

        if (currentUsername == null) {
            out.write("未登录用户不能修改信息");
            return;
        }

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            // 检查要修改的用户是否存在
            if (!userExists(conn, username)) {
                out.write("用户不存在");
                return;
            }

            // 如果不是管理员且不是修改自己的信息
            if (!"admin".equals(role) && !username.equals(currentUsername)) {
                out.write("无权修改其他用户信息");
                return;
            }

            // 更新用户信息
            String sql = "UPDATE users SET email = ?, phone = ? WHERE username = ?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, email);
                ps.setString(2, phone);
                ps.setString(3, username);

                int rowsAffected = ps.executeUpdate();
                if (rowsAffected > 0) {
                    out.write("信息修改成功");
                } else {
                    out.write("修改失败");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.write("修改失败: " + e.getMessage());
        }
    }

    private boolean userExists(Connection conn, String username) throws SQLException {
        String sql = "SELECT 1 FROM users WHERE username = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, username);
            try (ResultSet rs = ps.executeQuery()) {
                return rs.next();
            }
        }
    }
}
